package com.htudata.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionUtils {

  public static String sendPost(String URL, String requestJson) throws Exception {
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    StringBuffer sb = null;
    try {
      CustomX509TrustManager.init();
      URL url = new URL(URL);
      connection = (HttpURLConnection)url.openConnection();
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setUseCaches(false);
      connection.setInstanceFollowRedirects(true);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Accept", "application/json");
      connection.setRequestProperty("Content-Type", "application/json");
      connection.setReadTimeout(10000);
      connection.setConnectTimeout(10000);
      connection.connect();
      OutputStreamWriter out = null;
      try {
        out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        out.write(requestJson);
        out.flush();
      } catch (Exception e) {
        throw e;
      } finally {
        try {
          if (out != null) {
            out.close();
            out = null;
          } 
        } catch (IOException e) {

        } 
      } 
      reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      sb = new StringBuffer("");
      String lines;
      while ((lines = reader.readLine()) != null) {
        lines = new String(lines.getBytes(), "utf-8");
        sb.append(lines);
      } 
    } catch (Exception e) {
      throw e;
    } finally {
      if (reader != null)
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }  
      if (connection != null)
        connection.disconnect(); 
    } 
    return sb.toString();
  }
}
